'use client';

import React, { useState } from 'react';
import { useCollaboration } from '@/hooks/use-collaboration';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { format } from 'date-fns';
import { Check, X, MessageSquare, FileText } from 'lucide-react';
import { toast } from '@/components/ui/use-toast';

interface DocumentSuggestionsProps {
  documentId: string;
  projectId: string;
  className?: string;
  currentContent?: any;
  userPermission?: string;
  onApplySuggestion?: (suggestion: any) => Promise<boolean | void>;
}

export function DocumentSuggestions({ 
  documentId, 
  projectId, 
  className = '',
  currentContent,
  userPermission,
  onApplySuggestion 
}: DocumentSuggestionsProps) {
  const { suggestions, resolveSuggestion, editor } = useCollaboration();
  const [resolving, setResolving] = useState<Record<string, boolean>>({});
  const [currentTab, setCurrentTab] = useState<'pending' | 'accepted' | 'rejected'>('pending');
  
  // 获取过滤后的建议列表
  const filteredSuggestions = suggestions.filter(s => s.status === currentTab);
  
  // 处理接受建议
  const handleAcceptSuggestion = async (suggestionId: string) => {
    if (!editor) return;
    
    setResolving(prev => ({ ...prev, [suggestionId]: true }));
    
    try {
      // 查找建议
      const suggestion = suggestions.find(s => s.id === suggestionId);
      if (!suggestion) return;
      
      // 应用建议内容
      if (suggestion.suggestedContent) {
        // 根据建议操作类型应用不同的处理逻辑
        if (suggestion.suggestedOperation === 'replace') {
          // 如果有节点ID，则替换特定节点内容
          if (suggestion.nodeId) {
            // 在实际项目中，这里需要实现节点内容替换逻辑
            // 这里使用简化的实现
            console.log('替换节点内容:', suggestion.nodeId, suggestion.suggestedContent);
          } else if (suggestion.range) {
            // 替换范围内的内容
            console.log('替换范围内容:', suggestion.range, suggestion.suggestedContent);
          }
        } else if (suggestion.suggestedOperation === 'insert') {
          // 插入内容
          console.log('插入内容:', suggestion.suggestedContent);
        } else if (suggestion.suggestedOperation === 'delete') {
          // 删除内容
          console.log('删除内容:', suggestion.nodeId || suggestion.range);
        }
      }
      
      // 解决建议
      await resolveSuggestion(suggestionId, true);
      
      toast({
        title: '已接受建议',
        description: '建议内容已应用到文档中'
      });
    } catch (error) {
      console.error('接受建议失败:', error);
      toast({
        title: '操作失败',
        description: '无法接受此建议',
        variant: 'destructive'
      });
    } finally {
      setResolving(prev => ({ ...prev, [suggestionId]: false }));
    }
  };
  
  // 处理拒绝建议
  const handleRejectSuggestion = async (suggestionId: string) => {
    setResolving(prev => ({ ...prev, [suggestionId]: true }));
    
    try {
      await resolveSuggestion(suggestionId, false);
      
      toast({
        title: '已拒绝建议',
        description: '建议已被拒绝'
      });
    } catch (error) {
      console.error('拒绝建议失败:', error);
      toast({
        title: '操作失败',
        description: '无法拒绝此建议',
        variant: 'destructive'
      });
    } finally {
      setResolving(prev => ({ ...prev, [suggestionId]: false }));
    }
  };
  
  // 获取用户初始字母（用于头像）
  const getUserInitials = (name: string) => {
    return name
      .split(' ')
      .map(part => part[0])
      .join('')
      .toUpperCase()
      .substring(0, 2);
  };
  
  // 渲染建议状态徽章
  const renderStatusBadge = (status: string) => {
    switch (status) {
      case 'pending':
        return <Badge variant="outline" className="bg-yellow-100 text-yellow-800 border-yellow-200">待处理</Badge>;
      case 'accepted':
        return <Badge variant="outline" className="bg-green-100 text-green-800 border-green-200">已接受</Badge>;
      case 'rejected':
        return <Badge variant="outline" className="bg-red-100 text-red-800 border-red-200">已拒绝</Badge>;
      default:
        return null;
    }
  };
  
  // 渲染建议操作类型
  const renderOperationType = (operation: string) => {
    switch (operation) {
      case 'replace':
        return '替换内容';
      case 'insert':
        return '插入内容';
      case 'delete':
        return '删除内容';
      default:
        return '修改内容';
    }
  };
  
  // 渲染建议列表
  const renderSuggestionList = () => {
    if (filteredSuggestions.length === 0) {
      return (
        <div className="py-8 text-center text-muted-foreground">
          <p>暂无{currentTab === 'pending' ? '待处理' : currentTab === 'accepted' ? '已接受' : '已拒绝'}的建议</p>
        </div>
      );
    }
    
    return (
      <ScrollArea className="h-[300px]">
        <div className="space-y-4 pr-4">
          {filteredSuggestions.map(suggestion => (
            <Card key={suggestion.id} className="overflow-hidden">
              <CardHeader className="bg-muted/30 pb-2">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Avatar className="h-6 w-6">
                      {suggestion.author.image ? (
                        <AvatarImage src={suggestion.author.image} alt={suggestion.author.name} />
                      ) : (
                        <AvatarFallback>{getUserInitials(suggestion.author.name)}</AvatarFallback>
                      )}
                    </Avatar>
                    <CardTitle className="text-sm font-medium">
                      {suggestion.author.name}
                    </CardTitle>
                    <CardDescription className="text-xs">
                      {format(new Date(suggestion.timestamp), 'yyyy-MM-dd HH:mm')}
                    </CardDescription>
                  </div>
                  <div className="flex items-center gap-2">
                    {renderStatusBadge(suggestion.status)}
                    <Badge variant="outline" className="text-xs">
                      {renderOperationType(suggestion.suggestedOperation)}
                    </Badge>
                  </div>
                </div>
              </CardHeader>
              
              <CardContent className="py-3">
                <div className="text-sm mb-2">
                  <strong>建议说明:</strong> {suggestion.note || '无说明'}
                </div>
                
                <div className="grid grid-cols-2 gap-2">
                  <div className="border rounded p-2 bg-muted/20">
                    <div className="text-xs text-muted-foreground mb-1">原内容</div>
                    <pre className="text-xs overflow-auto max-h-24 whitespace-pre-wrap">
                      {JSON.stringify(suggestion.originalContent, null, 2)}
                    </pre>
                  </div>
                  <div className="border rounded p-2 bg-green-50">
                    <div className="text-xs text-muted-foreground mb-1">建议内容</div>
                    <pre className="text-xs overflow-auto max-h-24 whitespace-pre-wrap">
                      {JSON.stringify(suggestion.suggestedContent, null, 2)}
                    </pre>
                  </div>
                </div>
              </CardContent>
              
              {suggestion.status === 'pending' && (
                <CardFooter className="flex justify-end gap-2 pt-0 pb-3">
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleRejectSuggestion(suggestion.id)}
                    disabled={resolving[suggestion.id]}
                  >
                    <X className="h-4 w-4 mr-1" />
                    拒绝
                  </Button>
                  <Button
                    size="sm"
                    onClick={() => handleAcceptSuggestion(suggestion.id)}
                    disabled={resolving[suggestion.id]}
                  >
                    <Check className="h-4 w-4 mr-1" />
                    接受
                  </Button>
                </CardFooter>
              )}
            </Card>
          ))}
        </div>
      </ScrollArea>
    );
  };
  
  return (
    <div className={`space-y-4 ${className}`}>
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-medium flex items-center gap-2">
          <FileText className="h-5 w-5" />
          <span>文档建议</span>
        </h3>
        <Badge>
          {suggestions.filter(s => s.status === 'pending').length} 个待处理
        </Badge>
      </div>
      
      <Tabs value={currentTab} onValueChange={(value) => setCurrentTab(value as any)}>
        <TabsList className="grid grid-cols-3 w-full">
          <TabsTrigger value="pending">
            待处理 ({suggestions.filter(s => s.status === 'pending').length})
          </TabsTrigger>
          <TabsTrigger value="accepted">
            已接受 ({suggestions.filter(s => s.status === 'accepted').length})
          </TabsTrigger>
          <TabsTrigger value="rejected">
            已拒绝 ({suggestions.filter(s => s.status === 'rejected').length})
          </TabsTrigger>
        </TabsList>
        
        <TabsContent value={currentTab}>
          {renderSuggestionList()}
        </TabsContent>
      </Tabs>
    </div>
  );
}